<?php

use App\V3\Api\Models\AdminAddendumModel;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

//公共函数
/**
 * change 在 2021/9/24 11:02 创建
 * @param string $data 返回数据
 * @param string $msg 返回提示
 * @return \Illuminate\Http\JsonResponse
 */
function success($data = '', $msg = 'success', $code = 0)
{
    return response()->json([
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
    ]);
}

/**
 * change 在 2021/9/24 11:18 创建
 * @param string $data 响应参数
 * @param string $msg 响应提示
 * @return \Illuminate\Http\JsonResponse
 */
function fail($data = '', $msg = 'fail', $code = 1)
{
    return response()->json([
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
    ]);
}

/**
 * 统计客户上传文件占的空间大小
 * @param  $condition （条件查询传 ['main_id'=>$this->getMainUserId()] ）
 * @param  $size      当前图片占空间的大小
 * @param $path 图片路径
 *
 */
function saveFileSize($condition, $size, $path)
{

    $model = AdminAddendumModel::select('account_storage', 'file_total_size')->where($condition)->first();
    if ($model->file_total_size >= $model->account_storage) {
        return ['code' => 1, 'msg' => "无可用存储空间", 'data' => ''];
    }

    $residualSize = $model->account_storage - $model->file_total_size;
    if ($size > $residualSize) {
        return ['code' => 1, 'msg' => "剩余可用存储空间不足", 'data' => ''];
    }

    DB::beginTransaction();

    try {
        AdminAddendumModel::where($condition)
            ->increment('file_total_size', $size);

        DB::commit();
        return ['code' => 0, 'msg' => "success", 'data' => ''];
    } catch (Exception $e) {
        Log::debug('存储空间异常' . var_export($e->getMessage(), true));
        DB::rollBack();

        return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
    }
}

/**
 * 处理上传文件类型
 */
function handleUploadFileType($file)
{

    $video_format = 'flash,mpeg,mpeg-2,mpeg-4,midi,wmv,asf,asx,rm,rmvb,mp4,3gp,mov,m4v,avi,dat,mkv,flv,vob';

    $pic_format = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp,avif,apng';

    $music_format = 'mp3,aac,wav,wma,cda,flac,m4a,mid,mka,mp2,mpa,mpc,ape,ofr,ogg,ra,wv,ac3,dts';

    $ext = $file->extension();

    $ext = strtolower($ext);

    $pic_arr = explode(',', $pic_format);
    $video_arr = explode(',', $video_format);
    $music_arr = explode(',', $music_format);

    $size = $file->getSize();
    $msg = "";
    if (in_array($ext, $pic_arr)) {

        if ($size > 10485760) {

            $msg = '图片大小不能超出10M';
        }

    } elseif (in_array($ext, $video_arr)) {

        if ($size > 10485760) {

            $msg = '视频大小不能超出10M';
        }

    } elseif (in_array($ext, $music_arr)) {

        if ($size > 10485760) {

            $msg = '音乐大小不能超出10M';
        }
    }

    if (!empty($msg)) return ['code' => 1, 'msg' => $msg, 'data' => ''];
}

/**
 * 查询小数点后几位
 * @param unknown $data
 */
function getDecimalPointLeng($num)
{
    $arr = explode('.', $num);
    $str = array_pop($arr);
    $len = strlen($str);
    return $len;
}

//上传多个图片
function uploadImgs($request, $data, $ossClient, $param = '')
{
    if (!empty($imgfile = $request->file($param))) {
        $imgArr = [];
        foreach ($imgfile as $v) {
            if ($v->isValid()) {
                $res = handlePicFormat($v, 'p', '图片格式，不正确！');

                if (!empty($res)) return $res;
                $imgPath = $v->store(date('Y') . '/' . date('m') . '/' . date('d'));

                $imgRes = addOssUploadImg($data['main_id'], $ossClient, $v, $imgPath);
                if ($imgRes['code'] == 1) return $imgRes;
                $imgArr[] = '/uploads/' . $imgPath;
            } else {
                return ['code' => 1, 'msg' => '上传失败', 'data' => ''];
            }
        }
        $imgArr = implode(',', $imgArr);
        return ['code' => 0, 'msg' => '上传成功', 'data' => $imgArr];
    } else {
        return ['code' => 1, 'msg' => '请选择图片上传', 'data' => ''];
    }
}

//上传单个图片
function uploadImg($request, $data, $ossClient, $param = '')
{
    if (!empty($imgfile = $request->file($param))) {
        $imgPath = '';
        if ($imgfile->isValid()) {
            $res = handlePicFormat($imgfile, 'p', '图片格式，不正确！');
            if (!empty($res)) return $res;
            $imgPath = $imgfile->store(date('Y') . '/' . date('m') . '/' . date('d'));
            $imgRes = addOssUploadImg($data['main_id'], $ossClient, $imgfile, $imgPath);
            if ($imgRes['code'] == 1) return $imgRes;
            $imgPath = '/uploads/' . $imgPath;
        } else {
            return ['code' => 1, 'msg' => '上传失败', 'data' => ''];
        }
        return ['code' => 0, 'msg' => '上传成功', 'data' => ['path' => $imgPath]];
    } else {
        return ['code' => 1, 'msg' => '请选择图片上传', 'data' => ''];
    }
}

//图片上传到oss系统
function addOssUploadImg($mainId, $client, $file, $path)
{
    $res = handleUploadFileType($file);
    if (!empty($res)) return $res;
    $size = $file->getSize();
    $result = saveFileSize(['main_id' => $mainId], $size, $path);
    if ($result['code'] == 1) return $result;
    try {
        $fullPath = '/uploads/' . $path;
        $ossPath = ltrim($fullPath, './');
        $path = public_path() . $fullPath;
        $client->uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);
        @unlink($path);
        $url = config('app.aliyun_oss_bucket_url') . $fullPath;
        return ["code" => 0, "msg" => "success", "data" => $url];
    } catch (\Exception $e) {
        return ["code" => 1, "msg" => "OSS系统，上传图片失败！", "data" => ""];
    }
}

/**
 * 处理图片和视频格式
 */
function handlePicFormat($files, $flag, $msg)
{
    $pic_video_format = 'mp3,aac,wav,wma,cda,flac,m4a,mid,mka,mp2,mpa,mpc,ape,ofr,ogg,ra,wv,ac3,dts,
                                    flash,mpeg,mpeg-2,mpeg-4,midi,wmv,asf,asx,rm,rmvb,mp4,3gp,mov,m4v,avi,dat,mkv,flv,vob,
                                    bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,
                                    ufo,eps,ai,raw,wmf,webp,avif,apng';
    $pic_format = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp,avif,apng';
    $music_format = 'mp3,aac,wav,wma,cda,flac,m4a,mid,mka,mp2,mpa,mpc,ape,ofr,ogg,ra,wv,ac3,dts';
    $ext = $files->extension();
    $ext = strtolower($ext);
    if ($flag == 'm') {
        $pic_video_format_arr = explode(',', $music_format);
    } elseif ($flag == 'p') {
        $pic_video_format_arr = explode(',', $pic_format);
    } else {
        $pic_video_format_arr = explode(',', $pic_video_format);
    }
    if (!in_array($ext, $pic_video_format_arr)) {
        return ['code' => 1, 'msg' => $msg, 'data' => ''];
    }
}

function getNO($table, $param)
{
    $no = (int)substr(Carbon::now()->year, -2).date('mdHis', time()) . random_int(1, 9);
    do {
        $no = (int)substr(Carbon::now()->year, -2).date('mdHis', time()) . random_int(1, 9);
    } while (DB::table($table)->where($param, $no)->exists());
    return $no;
}
